#include "lineedit.h"
#include <QDebug>

static RegisterElementType r("LineEdit", LineEdit());

LineEdit::LineEdit(Element *parent)
    :Element(parent)
    ,backspace_key_(-1)
{
    connect(this, &LineEdit::keyEvent, this, &LineEdit::onKeyEvent);
}

bool LineEdit::copyFrom(const Element *e)
{
    const LineEdit *le = qobject_cast<const LineEdit*>(e);
    if(!le) return false;

    text_ = le->text_;
    backspace_key_ = le->backspace_key_;
    alpha_keys_ = le->alpha_keys_;
    number_keys_ = le->number_keys_;

    return Element::copyFrom(le);
}

Element *LineEdit::clone() const
{
    LineEdit *le = new LineEdit;
    if(!le->copyFrom(this)){
        delete le;
        le = NULL;
    }
    return le;
}

void LineEdit::setText(const QString &text)
{
    text_ = text;
}

QString LineEdit::text() const
{
    return text_;
}

void LineEdit::setBackspaceKey(int key)
{
    backspace_key_ = key;
    bindKey(key);
}

int LineEdit::backspaceKey() const
{
    return backspace_key_;
}

void LineEdit::setAlphaKeys(QList<int> keys)
{
    alpha_keys_ = keys;
    bindKeys(keys);
}

QList<int> LineEdit::alphaKeys() const
{
    return alpha_keys_;
}

void LineEdit::setNumberKeys(QList<int> keys)
{
    number_keys_ = keys;
    bindKeys(keys);
}

QList<int> LineEdit::numberKeys() const
{
    return number_keys_;
}

QRect LineEdit::sizeHint() const
{
    return QRect(rect_.x(), rect_.y(), text().length(), 1);
}

void LineEdit::paintEvent()
{
    if(hasFocus())
        writeText(rect(), text(), Color(255, 0, 0));
    else
        writeText(rect(), text());
}

void LineEdit::onKeyEvent(int key, int value)
{
    if(!hasBindKey(key)){
        qWarning() << Q_FUNC_INFO << QString("Unknow key event (%1, %2)").arg(key).arg(value);
    }else{
        if(isAlphaKey(key)){
            text_ += 'a' + alphaKeys().indexOf(key);
        }else if(isNumberKey(key)){
            text_ += '0' + numberKeys().indexOf(key);
        }else if(isBackspaceKey(key)){
            text_.truncate(text_.length()-1);
        }else{
            qWarning() << Q_FUNC_INFO <<
                          QString("Unknow key %1 for LineEdit").arg(key);
        }
        update();
    }
}

QString LineEdit::getSignalSignature(const QString &name) const
{
    if(name=="textChanged"){
        return SIGNAL(textChanged());
    }else{
        return Element::getSignalSignature(name);
    }
}
